//
//  BanBu_RegFirstViewController.m
// Halfarea
//
//  Created by banbu3 on 14-2-10.
//
//

#import "BanBu_RegFirstViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_SetAvatarViewController.h"
#import "BanBu_DetailProfileViewController.h"
@interface BanBu_RegFirstViewController ()
{
//    CGFloat keyboardHeight;
//    UIImageView *goNext;
//    UIActivityIndicatorView *loading;
    
}
@end

@implementation BanBu_RegFirstViewController
//#define TABLECOLOR [UIColor colorWithRed:78.0/255.0 green:201.0/255.0 blue:171.0/255.0 alpha:1]
//#define TABLECOLOR [UIColor colorWithRed:0.929 green:0.799 blue:0.181 alpha:1.000]
#define TABLECOLOR [UIColor colorWithRed:0.879 green:0.442 blue:0.774 alpha:1.000]


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)keyboardWasShow:(NSNotification *)notification
{
    CGRect keyboardFrames = [[[notification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardHeight = keyboardFrames.size.height;
//    [self.tableView setContentOffset:CGPointMake(0,self.tableView.contentSize.height-( __MainScreen_Height-keyboardHeight-44))];

    [self autoLayoutTableView];
}

-(void)keyboardWasHidden:(NSNotification *)notification
{
//     CGRect keyboardFrames = [[[notification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardHeight = 0;
//    [self.tableView setContentOffset:CGPointMake(0, 0)];
    [self autoLayoutTableView];
}
-(void)hideDatePicker
{
    [self hideBirthdayPicker:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"regTitle", nil);
//    self.navigationController.navigationItem.titleView
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasShow:) name:UIKeyboardDidShowNotification object:nil];
    
    
    UITableView *tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44)];
    tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    tab.backgroundColor = TABLECOLOR;
    tab.delegate = self;
    tab.dataSource = self;
    [self.view addSubview:tab];
    self.tableView = tab;
    self.view.backgroundColor = TABLECOLOR;
    
    
    UIDatePicker *datePicker = [ [ UIDatePicker alloc] initWithFrame:CGRectMake(0.0,__MainScreen_Height,0.0,0.0)];
    
    datePicker.backgroundColor = [UIColor whiteColor];
    self.birthdayPicker = datePicker;
    [datePicker addTarget:self action:@selector(dateDidChanged:) forControlEvents:UIControlEventValueChanged];
//    [datePicker addTarget:self action:@selector(hideDatePicker) forControlEvents:UIControlEventEditingDidEndOnExit];
    datePicker.datePickerMode = UIDatePickerModeDate;
    NSLocale* locale=[[NSLocale alloc]initWithLocaleIdentifier:[MyAppDataManager getPreferredLanguage]];
    [datePicker setLocale:locale];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setLocale:[NSLocale currentLocale]];
    
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    NSString *dateStr1 = [dateStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:[NSString stringWithFormat:@"%i",[[dateStr substringToIndex:4] intValue]-16]];
    
    NSString *dateStr2 = [dateStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:[NSString stringWithFormat:@"%i",[[dateStr substringToIndex:4] intValue]-100]];
    
    NSDate *maxDate = [formatter dateFromString:dateStr1];
    NSDate *minDate = [formatter dateFromString:dateStr2];
    datePicker.maximumDate = maxDate;
    datePicker.minimumDate = minDate;
    [datePicker setAccessibilityLanguage:@""];
    
    NSDate *maxiDate = [NSDate dateWithTimeInterval:-(24*60*60) sinceDate:maxDate];

    datePicker.date = maxiDate;

    [locale release];
    [formatter release];
    [self.view addSubview:datePicker];
    [datePicker release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideDatePicker)];
    [datePicker addGestureRecognizer:tap];
    [tap release];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)contentSizeToFit:(UITextView *)answerTextView
{
    if([answerTextView.text length]>0) {
//        CGSize contentSize = [answerTextView sizeThatFits:CGSizeMake(answerTextView.frame.size.width, 70)];
        CGSize contentSize = answerTextView.contentSize;
        NSLog(@"w:%f h%f",contentSize.width,contentSize.height);
        UIEdgeInsets offset;
        CGSize newSize = contentSize;
        if(contentSize.height <= answerTextView.frame.size.height) {
            CGFloat offsetY = (answerTextView.frame.size.height - contentSize.height)/2;
            offset = UIEdgeInsetsMake(offsetY, 0, 0, 0);
        }
        else {
            newSize = answerTextView.frame.size;
            offset = UIEdgeInsetsZero;
            CGFloat fontSize = 18;
            while (contentSize.height > answerTextView.frame.size.height) {
                [answerTextView setFont:[UIFont fontWithName:@"Helvetica Neue" size:fontSize--]];
                contentSize = answerTextView.contentSize;
            }
            newSize = contentSize;
        }
        [answerTextView setContentSize:newSize];
        [answerTextView setContentInset:offset];
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 3)
    {
        static NSString *cellIndentifer = @"cellindentifier111";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifer];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifer];
            cell.backgroundColor = [UIColor clearColor];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        UIView *b = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 70)];
        b.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:b];
        [b release];
        
        UILabel *noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 290,70)];
        noticeLabel.tag = 101;
        noticeLabel.numberOfLines = 0;
        noticeLabel.backgroundColor = [UIColor whiteColor];
        noticeLabel.text = NSLocalizedString(@"bottomNotice", nil);
        noticeLabel.textColor = [UIColor blackColor];
        
        noticeLabel.font = [UIFont systemFontOfSize:13];
        noticeLabel.textAlignment = kTextAlignmentLeft;
        noticeLabel.backgroundColor = [UIColor clearColor];
        [b addSubview:noticeLabel];
        [noticeLabel release];
        
//        UITextView * headerText = [[UITextView alloc]initWithFrame:CGRectMake(15, 0, 290,70)];
//        headerText.backgroundColor = [UIColor whiteColor];
//        headerText.font = [UIFont systemFontOfSize:13];
//         headerText.textColor = [UIColor blackColor];
//        
//        headerText.userInteractionEnabled = NO;
//        headerText.editable = NO;
//        headerText.textAlignment = kTextAlignmentLeft;
//        headerText.text = NSLocalizedString(@"bottomNotice", nil);
//        [self contentSizeToFit:headerText];
//        [b addSubview:headerText];
//        
//        [headerText release];
//
        forthCell = cell;
        forthView = b;
        return cell;
    }
    else
    {
        static NSString *cellIndentifer = @"cellindentifier";
        BanBu_RegisterCell *cell = (BanBu_RegisterCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifer];
        if(!cell)
        {
            cell = [[BanBu_RegisterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifer];
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
        }
        if(indexPath.row == 0)
        {
            cell.textField.placeholder = NSLocalizedString(@"emailLabel", nil);
            emailField = cell.textField;
        }
        else if(indexPath.row == 1)
        {
            cell.textField.placeholder = NSLocalizedString(@"errorMsg3", nil);
            passField = cell.textField;
        }
        else if(indexPath.row == 2)
        {
            cell.textField.placeholder = NSLocalizedString(@"birthdayTitle", nil);
            cell.textField.userInteractionEnabled = NO;
            dateLabel = cell.errorLabel;
        }
//        if(indexPath.row == 2)
//        {
//            cell.textField.hidden = YES;
//            cell.errorLabel.hidden = NO;
//            cell.errorLabel.textColor = [UIColor blackColor];
//        }
        return cell;
    }

    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 72;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.row == 2)
    {
        [self hideBirthdayPicker:NO];
    }
    else if(indexPath.row == 3)
    {
        [passField resignFirstResponder];
        [emailField resignFirstResponder];
    }
    else
    {
        [self hideBirthdayPicker:YES];
    }
}

-(void)dateDidChanged:(UIDatePicker *)picker
{
    [self showBirthDateString];
    [self checkIfCanNext];
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dateStr = [formatter1 stringFromDate:[NSDate date]];
    
    NSString *dateStr1 = [dateStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:[NSString stringWithFormat:@"%i",[[dateStr substringToIndex:4] intValue]-16]];
    NSString *dateStr2 = [dateStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:[NSString stringWithFormat:@"%i",[[dateStr substringToIndex:4] intValue]-100]];
    //    dateStr = [dateStr stringByReplacingCharactersInRange:NSMakeRange(8, 2) withString:[NSString stringWithFormat:@"%d",[[dateStr substringFromIndex:8]intValue]-1]];
    NSDate *maxiDate = [formatter1 dateFromString:dateStr1];
    NSDate *maxDate = [NSDate dateWithTimeInterval:-(24*60*60) sinceDate:maxiDate];
    
    NSDate *minidate = [formatter1 dateFromString:dateStr2];
    NSDate *mindate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:minidate];
    
    [formatter1 release];
    
    picker.date = [mindate laterDate:picker.date];
    picker.date = [maxDate earlierDate:picker.date];
    
    
    NSDate *pickerDate = [NSDate dateWithTimeInterval:3600*12 sinceDate:picker.date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    dateLabel.text = [formatter stringFromDate:pickerDate];
    [formatter release];
}

-(void)cellTextFieldDidEditing:(UITextField *)textField
{
    [self checkIfCanNext];
}
-(void)setEnterButtonLoading:(BOOL)flag
{
    goNext.hidden = flag;
    loading.hidden = !flag;
    if(flag)
        [loading startAnimating];
    else
        [loading stopAnimating];
    
}
-(void)checkIfCanNext
{
    if(passField.text.length&&emailField.text.length&&dateLabel.text.length&&!isReadyNext)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 320, 70);
//        btn.backgroundColor = [UIColor redColor];
        [btn setBackgroundImage:[UIImage imageNamed:@"topbar.png"] forState:UIControlStateNormal];
        [btn setTitle:@"Enter" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:25];

        [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
        enterButton = btn;
        
        UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gonext.png"]];
        img.frame = CGRectMake(280, 22.5, 25, 25);
        [btn addSubview:img];
        goNext = img;
        [img release];
        
        UIActivityIndicatorView *a = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        a.frame = CGRectMake(280, 22.5, 25, 25);
        [btn addSubview:a];
        a.hidden = YES;
        loading = a;
        [a release];
        
        UIView *aview = [[UIView alloc] init];
        aview.backgroundColor = TABLECOLOR;
        aview.frame = CGRectMake(0, 0, 320, 70);
        
        [forthCell addSubview:btn];
        [forthCell addSubview:aview];
        
        
        [aview release];
        
        forthView.hidden = YES;
        isReadyNext = YES;
        
            [UIView animateWithDuration:.3 animations:^{
            
            aview.frame = CGRectMake(320, 0,320, 70);
        } completion:^(BOOL finished) {
            [aview removeFromSuperview];
        }];
    }
    else if((!passField.text.length||!emailField.text.length||!dateLabel.text.length)&&isReadyNext)
    {
        UIView *aview = [[UIView alloc] init];
        aview.backgroundColor = TABLECOLOR;
        aview.frame = CGRectMake(320, 0, 320, 70);
        
        [forthCell addSubview:aview];
        
        
        isReadyNext = NO;
        
            [UIView animateWithDuration:.3 animations:^{
            aview.frame = CGRectMake(0, 0,320, 70);
        } completion:^(BOOL finished) {
            
            [enterButton removeFromSuperview],enterButton = nil;
            forthView.hidden = NO;
            [aview removeFromSuperview];
        }];
    }
}

-(void)cellTextFieldBeginEditing:(UITextField *)textField andCell:(BanBu_RegisterCell *)cell
{
    [self hideBirthdayPicker:YES];
    [cell cancelError:nil];
    
}

-(void)autoLayoutTableView
{
    CGFloat tableHeight = 0;
    tableHeight = self.birthdayPicker.frame.origin.y<__MainScreen_Height?__MainScreen_Height-44-216:__MainScreen_Height;
    if(keyboardHeight != 0)
    {
        tableHeight = __MainScreen_Height - 44 - keyboardHeight;
    }

    self.tableView.frame = CGRectMake(0, 0, 320,tableHeight);
//    if(tableHeight != __MainScreen_Height)
//    {
//        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
////
//    }
}

-(void)hideBirthdayPicker:(BOOL)h
{

    if(!h)
    {
            [UIView animateWithDuration:.3 animations:^{

            [passField resignFirstResponder];
            [emailField resignFirstResponder];
            [self.birthdayPicker becomeFirstResponder];
            self.birthdayPicker.frame = CGRectMake(0, __MainScreen_Height-260, 0, 0);
//            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

            [self.tableView setContentOffset:CGPointMake(0,self.tableView.contentSize.height-( __MainScreen_Height-self.birthdayPicker.frame.size.height-44))];
        } completion:^(BOOL finished) {
            [self autoLayoutTableView];
        }];
    }
    else
    {
            [UIView animateWithDuration:.3 animations:^{
            [self.birthdayPicker resignFirstResponder];
            self.birthdayPicker.frame = CGRectMake(0, __MainScreen_Height,0, 0);
            
            [self.tableView setContentOffset:CGPointMake(0,0)];

        } completion:^(BOOL finished) {
            [self autoLayoutTableView];
        }];
    }
//     [self autoLayoutTableView];

}

-(void)showBirthDateString
{
    BanBu_RegisterCell *cell = (BanBu_RegisterCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    cell.textField.hidden = YES;
    cell.errorLabel.hidden = NO;
    cell.errorLabel.textColor = [UIColor blackColor];
    dateLabel.text = @"1990-12-21";
}

-(void)checkEmailAvailable
{
    NSString *errorMsg = nil;
    if(!emailField.text.length)
    {
        errorMsg = NSLocalizedString(@"errorMsg", nil);
    }
    if(![self validateEmail:emailField.text])
    {
        errorMsg = NSLocalizedString(@"errorMsg1", nil);
    }

    if(errorMsg)
    {
        [emailField becomeFirstResponder];
        [self showError:errorMsg];
        [self setErrorCellIndex:0];
        [self setEnterButtonLoading:NO];
        return;
    }

    
    NSMutableDictionary *checkDic = [NSMutableDictionary dictionary];
    [checkDic setValue:emailField.text forKey:@"email"];
    
    [AppComManager getBanBuData:BanBu_Check_Email par:checkDic delegate:self];
    self.navigationController.view.userInteractionEnabled = NO;
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"detectEmail", nil) activityAnimated:YES];
    
}

- (void)showError:(NSString *)errorMsg
{
    [TKLoadingView showTkloadingAddedTo:self.view title:errorMsg activityAnimated:NO duration:1.0];
}

- (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

-(void)setErrorCellIndex:(NSInteger)index
{
    BanBu_RegisterCell *cell = (BanBu_RegisterCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell setError];
}

-(void)nextStep
{
    [self hideBirthdayPicker:YES];
    [passField resignFirstResponder];
    [emailField resignFirstResponder];
    if(passField.text.length<6)
    {
        NSString *errorMsg = NSLocalizedString(@"errorMsg3", nil);
        [self showError:errorMsg];
        [self setErrorCellIndex:1];
        return;
    }
    [self setEnterButtonLoading:YES];
    [self checkEmailAvailable];

}
-(void)saveRegisterInfo
{
    [MyAppDataManager.regDic setValue:emailField.text forKey:@"email"];
    [MyAppDataManager.regDic setValue:passField.text forKey:@"pass"];
    [MyAppDataManager.regDic setValue:dateLabel.text forKey:@"borndate"];
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [self setEnterButtonLoading:NO];
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        return;
    }
    //NSLog(@"res:%@",resDic);
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Email])
    {
        if([[resDic valueForKey:@"ok"] boolValue]){
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"successEmail", nil) activityAnimated:NO duration:1.0];
            //保存信息并推下一页面
            [self saveRegisterInfo];
            BanBu_DetailProfileViewController *avatar = [[BanBu_DetailProfileViewController alloc] init];
            [self.navigationController pushViewController:avatar animated:YES];
            [avatar release];
        }
        else
        {
            [self setErrorCellIndex:0];
            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:2.0];
            [emailField becomeFirstResponder];
        }
    }
    else
    {

        
    }
}

@end
